package common;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;

public abstract class AbstractFetcher {
	
	private final URL url;
	private final Charset charset;
	
	public AbstractFetcher(String urlString, Charset charset) throws MalformedURLException{
		url = new URL(urlString);
		this.charset = charset;
	}
	
	public CharSequence getCharacters() throws IOException{
		InputStream input = getInputStream();
		return getCharacters(input);
	}
	
	public CharSequence getCharacters(InputStream inputStream) throws IOException{
		StringBuilder chars = new StringBuilder();
		BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, charset));
		String line;
		while ((line = reader.readLine()) != null) {
			chars.append(line);
		}
		reader.close();
		return chars;
	}
	
	public InputStream getInputStream() throws IOException{
		URLConnection urlConnection = url.openConnection();
		urlConnection.setConnectTimeout(Integer.MAX_VALUE);//Google app no pilla mas de 10 segundos xP
		urlConnection.setReadTimeout(Integer.MAX_VALUE);
		return urlConnection.getInputStream();
	}
}
